﻿using System;
using System.Collections.Generic;
using System.Linq;
using AutoMapper;
using SapaFinance.DTO;
using SapaFinance.Domain.BusinessLogic;
using SapaFinance.Domain.Model;
using SapaFinance.GenericRepository;
using SapaFinance.Domain.Extensions;

namespace SapaFinance.Services
{
    public interface IOrderService
    {
        IRequestService RequestService { get; set; }
        IEnumerable<OrderDTO> GetListDTO();
        void Insert(OrderDTO dto);
        OrderDTO CreateOrder(Guid[] requestsIDs);
        void Delete(Guid id);
        void Update(OrderDTO dto);
        IEnumerable<string> CheckOrderSum(OrderDTO dto);
    }

    public class OrderService : IOrderService
    {
        private readonly IEntityFactory _entityFactory;
        private readonly IMappingEngine _mappingEngine;
        private readonly IGenericRepository<Order, Guid> _orderRepository;
        private readonly IUnitOfWork _unitOfWork;

        public OrderService(IMappingEngine mappingEngine, IGenericRepository<Order, Guid> orderRepository, IUnitOfWork unitOfWork,
                            IEntityFactory entityFactory)
        {
            _orderRepository = orderRepository;
            _unitOfWork = unitOfWork;
            _entityFactory = entityFactory;
            _mappingEngine = mappingEngine;
        }

        #region IOrderService Members
        public ICreateOrderCompositeRule CreateOrderRule { get; set; }
        public IRequestService RequestService { get; set; }
        public ICurrencyService CurrencyService { get; set; }
        public IAgentService AgentService { get; set; }
        public IUserService UserService { get; set; }

        public void Update(OrderDTO dto)
        {
            var currencyType = CurrencyService.GetCurrency(dto.SelectedCurrency);
            var agent = AgentService.GetAgent(dto.SelectedAgent);
            var order = _orderRepository.GetById(dto.UID);
            var user = UserService.GetUser(dto.CurrentUser);
            if (user != null)
            {
                order.SetPayment(dto.Payment ?? dto.Payment.Value, currencyType);
                order.SetAgent(agent);
                order.PaymentPeriod = dto.PaymentPeriod;
                order.PaymentPurpose = dto.PaymentPurpose;
                order.Change(user);
                _orderRepository.Update(order);
                _unitOfWork.Flush();
            }
        }

        public IEnumerable<string> CheckOrderSum(OrderDTO dto)
        {
            var currency = CurrencyService.GetCurrency(dto.SelectedCurrency);
            var requests = dto.LinkedRequests.Select(x => RequestService.GetRequest(x));
            var z = requests.Aggregate(Money.Create(0,currency), (current, request) => current + request.GetNotPaidAmount());
            CreateOrderRule.SetObjectToMatch(z);
            CreateOrderRule.IsValid(Money.Create(dto.Payment.HasValue ? dto.Payment.Value : 0, currency));
            return CreateOrderRule.GetBrokenRules();
        }

        public IEnumerable<OrderDTO> GetListDTO()
        {
            var orders = _orderRepository.GetAll();
            return _mappingEngine.Map<IEnumerable<Order>, IEnumerable<OrderDTO>>(orders);
        }

        public void Insert(OrderDTO dto)
        {
            var order = _entityFactory.BuildOrder(dto);
            _orderRepository.Insert(order);
            _unitOfWork.Flush();
        }

        public OrderDTO CreateOrder(Guid[] requestsIDs)
        {
            var requests = requestsIDs.Select(x => RequestService.GetRequest(x)).ToList();
            return _mappingEngine.Map<IEnumerable<Request>, OrderDTO>(requests);
        }

        public void Delete(Guid id)
        {
            var order = _orderRepository.GetById(id);
            if (order != null)
            {
                _orderRepository.Delete(order);
                _unitOfWork.Flush();
            }
        }

        #endregion
    }
}